//file name : cli.c

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

#define DEFAULT_PORT 12321
#define MAXDATASIZE 1024

int main(int argc, char *argv[])
{
    int sockfd, numbytes;
    int port = DEFAULT_PORT;
    char buf[MAXDATASIZE];
    char cmd[MAXDATASIZE];
    struct hostent *he;
    struct sockaddr_in their_addr;
    if (argc  == 1)
    {
        he = gethostbyname("localhost");
    }
    else if (argc == 2 || argc  == 3)
    {
        if ((he = gethostbyname(argv[1]))==NULL)
        {
            perror("gethostbyname error");
            exit(1);
        }
        if (argc  == 3)
        {
            port = atoi(argv[2]);
        }
    }
    else
    {
        perror("param error");
        exit(1);
    }
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("socket create error");
        exit(1);
    }
    their_addr.sin_family = AF_INET;
    their_addr.sin_port = htons(port);
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
    bzero(&(their_addr.sin_zero),8);
    if (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)
    {
        perror("connect error");
        exit(1);
    }
    while (1)
    {
        printf("flycached> ");
        fgets(cmd, MAXDATASIZE, stdin);
        if (send(sockfd,cmd, strlen(cmd), 0) == -1)
        {
            error("send error");
        }
        if (( numbytes = recv(sockfd, buf, MAXDATASIZE, 0)) == -1)
        {
            perror("recv error");
            exit(1);
        }
        buf[numbytes] = '\0';
        if (strcmp(buf, "QUIT\r\n")  ==  0)
            break;
        printf("%s\r\n",buf);
    }
    close(sockfd);
}
